package pl.minim.unidefTreeData {
	import com.yahoo.astra.fl.controls.treeClasses.RootNode;	
	import com.yahoo.astra.fl.controls.treeClasses.LeafNode;	
	import com.yahoo.astra.fl.controls.treeClasses.BranchNode;	
	
	import pl.minim.unidefCMS.UnidefManager;
	
	import com.googlecode.milib.base.MLBaseClass;
	import com.yahoo.astra.fl.controls.Tree;
	import com.yahoo.astra.fl.controls.treeClasses.TNode;
	import com.yahoo.astra.fl.controls.treeClasses.TreeDataProvider;
	
	import flash.display.MovieClip;
	import flash.utils.ByteArray;		

	/**
	 * @author Marek Brun
	 */
	public class TreeData extends MLBaseClass {
		
		private var _mc:MovieClip;
		private var unidefData:UnidefManager;
		private var data:Object;
		private var treeView:Tree;
		
		public function TreeData(mc:MovieClip, xmlba:ByteArray) {
			this._mc=mc;
			unidefData=new UnidefManager();
			unidefData.setDataByByteArray(xmlba);
			
			data=unidefData.exportToRawData();
			dbg.log('data:'+dbg.link(data));
			
			treeView=mc.treeView;
			
			var treeData:TreeDataProvider=new TreeDataProvider();
			treeData.rootNode=getTNodeByObject(treeData, data, true);
			treeView.dataProvider=treeData;
			dbg.log(dbg.link(treeData.rootNode));
		}
		
		protected function repairLevels(node:TNode):void {
			if(node is BranchNode){
				var i:uint;
				var loop:TNode;
				for(i=0;i<BranchNode(node).children.length;i++){
					loop=BranchNode(node).children[i];
					loop.nodeLevel=node.nodeLevel+1;
					repairLevels(loop);
				}
			}
		}
		
		protected function getTNodeByObject(treeData:TreeDataProvider, obj:Object, isRoot:Boolean=false):TNode {
			var node:TNode;
			if(obj.childs.length){
				var branchNode:BranchNode;
				if(isRoot){
					branchNode=new RootNode(treeData);
				}else{
					branchNode=new BranchNode(treeData);
				}
				node=branchNode;
				var i:uint;
				var loop:Object;
				for(i=0;i<obj.childs.length;i++){
					loop=obj.childs[i];
					branchNode.addChildNode(getTNodeByObject(treeData, loop));
				}
				node=branchNode;
			}else{
				var leafNode:LeafNode=new LeafNode(treeData);
				node=leafNode;
			}
			node.label=obj.name;
			node.data=obj;
			if(isRoot){
				repairLevels(node);
			}
			return node;
		}
		
		public function get mc():MovieClip {  return _mc; }
		
	}
}
